module Rubtools
  module Tools
    class Git < Rubtools::Recipe
      register_methods %w(clone_all up_all print_repos)

      def initialize
        @git = which "git"

        @git_config = config.git
        raise "Add the key 'git' in the config file" unless @git_config

        @install_dir = @git_config.install_dir
        raise "Add the key install_dir: /path/to/folder" unless @install_dir
        raise "Git isn't installed" unless @git
        raise "Folder doesn't exists: #{@install_dir}" unless File.exists? @install_dir
      end

      ## Print all repositories
      def print_repos
        for repo in config.git.repositories
          success "#{repo.name}\t#{repo.url}"
        end
      end

      ## Cloning all repositories located into rubtools.yml
      #
      def clone_all
        for repo in config.git.repositories
          clone repo
        end
      end

      ## Pull all repositories located into rubtools.yml
      #
      def up_all
        for repo in config.git.repositories
          up repo
        end
      end

      private
      ## Cloning a specific repository
      #
      def clone repo
          repo_path = File.join @install_dir, repo.name

          unless File.exists? repo_path
            success "Cloning #{repo.name} from #{repo.url}"
            exec_without_output "#{@git} clone --recursive #{repo.url} #{repo_path}" do |status|
              success "> done" if status.success?
            end
          else
            success "Repository #{repo.name} already cloned"
          end
      end


      ## Pulling a specific repository
      #
      def up repo
          repo_path = File.join @install_dir, repo.name

          if File.exists? repo_path
            success "Pulling #{repo.name} repository"
            exec_without_output "GIT_DIR=#{File.join(repo_path, ".git")} #{@git} pull --recurse-submodules=yes" do |status|
              success "> done" if status.success?
            end
          else
            info "Repository #{repo.name} doensn't exists"
            clone repo
          end
      end
    end
  end
end

